package com.ddm.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ddm.entity.File;
import com.ddm.result.Result;
import com.ddm.service.FileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 丁丁猫
 * @version 1.0
 */
@RestController("AdminFileController")
@RequestMapping("/admin/file")
@Slf4j
public class FileController {
    @Autowired
    private FileService fileService;

    /**
     * 新增文档url
     *
     * @param file
     * @return
     */
    @PostMapping
    @ApiOperation("新增文档url")
    public Result<String> add(@RequestBody File file) {
        log.info("新增文档url");
        //如果file.getStandardId()在数据库里匹配，则不新增
        LambdaQueryWrapper<File> eq = new LambdaQueryWrapper<File>().eq(File::getStandardId, file.getStandardId());
        File fileExist = fileService.getOne(eq);
        if (fileExist != null) {
            return Result.error("该标准已经存在文档，请勿重复添加");
        }
        fileService.save(file);
        return Result.success();
    }

    /**
     * 修改文档url
     *
     * @param file
     * @return
     */
    @PutMapping
    @ApiOperation("修改文档url")
    public Result<String> update(@RequestBody File file) {
        log.info("修改文档url");
        fileService.updateById(file);
        return Result.success();
    }

    /**
     * 删除文档url
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除文档url")
    public Result<String> delete(@PathVariable("id") Long id) {
        log.info("删除文档url");
        fileService.removeById(id);
        return Result.success();
    }

    /**
     * 根据id查询文档url
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询文档url")
    public Result<File> getById(@PathVariable("id") Long id) {
        log.info("根据id查询文档url");
        File file = fileService.getById(id);
        return Result.success(file);
    }

    /**
     * 根据standardId查询文档url
     *
     * @param standardId
     * @return
     */
    @GetMapping("standardId")
    @ApiOperation("根据id查询文档url")
    public Result<File> getByStandardId(@RequestParam Long standardId) {
        log.info("根据id查询文档url");
        LambdaQueryWrapper<File> eq = new LambdaQueryWrapper<File>().eq(File::getStandardId, standardId);
        File file = fileService.getOne(eq);
        return Result.success(file);
    }
}
